<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部的添加按钮 -->
      <div>
        <!-- 添加按钮 -->
        <el-button type="primary" icon="Plus" @click="addPP">
          添加品牌
        </el-button>
      </div>
      <div>
        <!-- 表格组件 -->
        <el-table
          :data="tableData"
          style="width: 100%; margin: 10px 0"
          :border="true"
        >
          <el-table-column
            label="序号"
            width="100"
            align="center"
            type="index"
          />
          <el-table-column prop="tmName" label="品牌名称" min-width="180" />
          <el-table-column prop="logoUrl" label="品牌logo" min-width="300">
            <template #default="{ row }">
              <img :src="row.logoUrl" :alt="row.tmName" class="tableImg" />
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" min-width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                icon="Edit"
                @click="editData(row)"
              ></el-button>
              <el-popconfirm
                :title="`是否删除${row.tmName}`"
                width="250px"
                @confirm="delData(row.id)"
              >
                <template #reference>
                  <el-button type="primary" icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div>
        <!-- 分页组件 -->
        <Pagination
          v-model:page="currentPage"
          v-model:size="pageSize"
          :total="total"
          :background="true"
          @pagination="getHasList"
          @paginations="paginations"
        ></Pagination>
      </div>
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="ruleForm.id ? '修改' : '添加'"
      width="600"
    >
      <div>
        <el-form
          style="width: 80%"
          :model="ruleForm"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item label="品牌名称" prop="tmName" label-width="100px">
            <el-input v-model="ruleForm.tmName" placeholder="请输入品牌名称" />
          </el-form-item>
          <el-form-item label="品牌logo" prop="logoUrl" label-width="100px">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :limit="1"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-exceed="handleExceed"
            >
              <img
                v-if="ruleForm.logoUrl"
                :src="ruleForm.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="primary" @click="quxiao">取消</el-button>
        <el-button type="primary" @click="yesDialog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import Pagination from '@/components/pagination/index.vue'
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTardemark,
  reqAddUpadte,
  delTardemark,
} from '@/api/product/trademark'
import request from '@/utils/axios'
import {
  ElMessage,
  genFileId,
  FormRules,
  type UploadInstance,
  type UploadProps,
  type UploadRawFile,
} from 'element-plus'
import {
  getHas,
  getHasDataRecords,
  addTradeMark,
} from '@/api/product/trademark/type.ts'
export interface postUpload {
  code: number
  message: string | null
  data: string
  ok: boolean
}
export interface dataTs {
  id: number
  createTime: string
  updateTime: string
  tmName: string
  logoUrl: string
}

// 分页数据
let currentPage = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(101)
const tableData = ref<getHasDataRecords[]>([])
let dialogVisible = ref<boolean>(false)
let ruleForm = reactive<addTradeMark>({
  tmName: '',
  logoUrl: '',
})
const upload = ref<UploadInstance>()
let formRef = ref()
const validatorTnName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称大于等于2位'))
  }
}
const validatorLogo = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('请上传图片'))
  }
}
// 表单校验
const rules = reactive<FormRules<addTradeMark>>({
  tmName: [{ required: true, validator: validatorTnName, trigger: 'blur' }],
  logoUrl: [{ required: true, validator: validatorLogo, trigger: 'blur' }],
})
// 调取接口
const getHasList = async () => {
  const res: getHas = await reqHasTardemark(currentPage.value, pageSize.value)
  if (res.code === 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
onMounted(() => {
  getHasList()
})
const paginations = () => {
  currentPage.value = 1
  getHasList()
}
const addPP = () => {
  ruleForm.tmName = ''
  ruleForm.logoUrl = ''
  ruleForm.id = 0
  dialogVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
// 取消按钮
const quxiao = () => {
  dialogVisible.value = false
  ruleForm.tmName = ''
  ruleForm.logoUrl = ''
}
// 确定按钮
const yesDialog = async () => {
  await formRef.value.validate()
  const res: postUpload = await reqAddUpadte(ruleForm)
  if (res.code == 200) {
    dialogVisible.value = false
    ElMessage.success(ruleForm.id ? '修改成功' : '添加成功')
    getHasList()
  } else {
    ElMessage.error(ruleForm.id ? '修改失败' : '添加失败')
  }
}
// 修改
const editData = (row: dataTs) => {
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  // ruleForm.id = row.id
  // ruleForm.tmName = row.tmName
  // ruleForm.logoUrl = row.logoUrl

  // ES6语法合并对象
  Object.assign(ruleForm, row)
  dialogVisible.value = true
}

// 覆盖上一个上传图片
const handleExceed: UploadProps['onExceed'] = async (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  const formData = new FormData()
  formData.append('file', file)
  const res = await request.post<any, postUpload>(
    '/admin/product/fileUpload',
    formData,
  )
  if (res.code == 200) {
    ruleForm.logoUrl = res.data
  }
}
// 上传限制
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type == 'image/jpeg' || rawFile.type == 'image/png') {
    if (rawFile.size / 1024 / 1024 < 4) {
      ElMessage.success('上传成功')
      return true
    } else {
      ElMessage.error('上传文件大小请小于4M')
      return false
    }
  } else {
    return false
  }
}
//上传成功
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response, //返回的数据
) => {
  formRef.value.clearValidate('logoUrl')
  ruleForm.logoUrl = response.data
}
//删除确定
const delData = async (val: string) => {
  let res: postUpload = await delTardemark(val)
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getHasList()
  } else {
    ElMessage.error('删除失败')
  }
}
</script>
<style lang="scss" scoped>
.tableImg {
  width: 100px;
  height: 100px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 300px;
  height: 300px;
}
</style>
